package pswvclass.pswvandroid2.com.util;

/**
 * Created by Administrator on 2018/11/1.
 */

import android.util.Log;

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.Map;
import java.io.IOException;
import java.net.URLEncoder;
import java.io.ByteArrayOutputStream;

public class HttpUtils {
    private static String sessionid;

    public static String submitPostData(String strUrlPath) {
        try {
            URL ur2 = new URL(strUrlPath);
            HttpURLConnection httpURLConnection2 = (HttpURLConnection) ur2.openConnection();
            String cookieval = httpURLConnection2.getHeaderField("set-cookie");
            if (cookieval != null) {
                sessionid = cookieval.substring(0, cookieval.indexOf(";"));
            }

        } catch (Exception e) {
            //e.printStackTrace();
            e.printStackTrace();
            Log.v("++___ss", e + "");
        }
        return "-1";
    }

    /*
     * Function  :   发送Post请求到服务器
     * Param     :   params请求体内容，encode编码格式
     */
    public static String submitPostData(String strUrlPath, Map<String, String> params, String encode) {

        byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体


        try {
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           /* if(sessionid != null) {
                httpURLConnection.setRequestProperty("cookie", sessionid);
            }*/
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获得输出流，向服务器写入数据
            httpURLConnection.connect();
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if (response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream);                     //处理服务器的响应结果
            }

        } catch (Exception e) {
            //e.printStackTrace();
            e.printStackTrace();
            Log.v("++___ss", e + "");
        }
        return "-1";
    }

    public static String submitPostData(String strUrlPath, String encode) {

        try {

            URL url = new URL(strUrlPath);
            // 取得sessionid.
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置请求体的长度
            String data = "";
            httpURLConnection.setRequestProperty("Content-Length", data.length() + "");
            if (sessionid != null) {
                httpURLConnection.setRequestProperty("cookie", sessionid);
                Log.v("UserPerfect", sessionid);
            }
            httpURLConnection.connect();
            //获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data.getBytes());
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if (response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream);                     //处理服务器的响应结果
            }

        } catch (Exception e) {
            //e.printStackTrace();
            e.printStackTrace();
            Log.v("++___ss", e + "");
        }
        return "-1";
    }

    /*
     * Function  :   封装请求体信息
     * Param     :   params请求体内容，encode编码格式
     */
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    /*
     * Function  :   处理服务器的响应结果（将输入流转化成字符串）
     * Param     :   inputStream服务器的响应输入流
     */
    public static String dealResponseResult(InputStream in) throws IOException {

        // 底层流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int len = 0;
        byte[] buf = new byte[1024];

        while ((len = in.read(buf)) > 0) {
            baos.write(buf, 0, len);
        }

        String data = baos.toString();

        if (data.contains("gbk")) {
            return baos.toString("gbk");
        } else if (data.contains("utf-8")) {

            return baos.toString("utf-8");
        } else {
            return data;
        }


    }
}
